from rest_framework import serializers
from .models import Label,Article,Comment
from rest_framework.fields import SerializerMethodField
# SerializerMethodField 有一些数据不能从模型里面直接得到，需要额外定义方法得到

# 标签序列号器
# 标签有存在的模型

class LabelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Label
        fields = '__all__'


# 文章序列号器
class ArticleSerializer(serializers.ModelSerializer):
    # 添加作者的头像
    user_avatar = serializers.CharField(read_only=True, source='user.userdetail.avatar')
    # 作者的名字
    user_name = serializers.CharField(read_only=True, source='user.username')
    class Meta:
        model = Article
        exclude = ["is_delete"]
        extra_kwargs = {
            "page_view":{"read_only": True},
            "priority":{"read_only": True},
        }


# 针对于子级评论使用
class SonCommentSerializer(serializers.ModelSerializer):
    # 添加作者的头像
    user_avatar = serializers.CharField(read_only=True, source='user.userdetail.avatar')
    # 作者的名字
    user_name = serializers.CharField(read_only=True, source='user.username')
    # 被回复人的名字
    repy_username = serializers.CharField(read_only=True,source="reply_comment.user.username")
    class Meta:
        model = Comment
        exclude = ["is_delete"]

# 评论序列器 只针对一级评论使用
class CommentSerializer(serializers.ModelSerializer):
    # 添加作者的头像
    user_avatar = serializers.CharField(read_only=True, source='user.userdetail.avatar')
    # 作者的名字
    user_name = serializers.CharField(read_only=True, source='user.username')

    son_comment_count = SerializerMethodField(read_only=True)
    class Meta:
        model = Comment
        exclude = ["is_delete"]


    # 方法名 和 son_comment_count字段名保持一致 ,前面还要加一个 get
    def get_son_comment_count(self, comment): # comment 当前所操作的模型对象
        return  comment.parent_comment_set.count()